package org.example.config;

import org.example.annotation.KafkaProcesser;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @author jingjing.zhang
 */
@Configuration
public class KafkaProcessCacheConfig implements ApplicationContextAware {
    private ApplicationContext applicationContext;
    private Map<String,String> processCache = new HashMap<>(16);;
    @Bean(name = "kafkaProcessCache")
    KafkaProcessCache kafkaProcessCache(){
        KafkaProcessCache KafkaProcessCache = new KafkaProcessCache();
        KafkaProcessCache.processCache = processCache;
        return KafkaProcessCache;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if (applicationContext == null){
            return;
        }
        String[] beans = applicationContext.getBeanNamesForAnnotation(KafkaProcesser.class);
        for (String bean: beans) {
            String key = applicationContext.findAnnotationOnBean(bean,KafkaProcesser.class).key();
            processCache.put(key,bean);
        }
    }

    public class KafkaProcessCache {
        public Map<String,String> processCache;
    }
}
